package com.bitcat.firstapp.demo.broadcastdemo

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.bitcat.firstapp.databinding.ActivityBroadcastOneBinding
import es.dmoral.toasty.Toasty

class BroadcastOneActivity : AppCompatActivity() {

    private val binding: ActivityBroadcastOneBinding by lazy {
        ActivityBroadcastOneBinding.inflate(layoutInflater)
    }

    private val messageReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            val action = intent.action
            if ("com.bitcat.message" == action){
                binding.tvMessage.text = intent.getStringExtra("name")
                Toasty.success(this@BroadcastOneActivity,"接收到广播").show()
            }
            else if (ConnectivityManager.CONNECTIVITY_ACTION == action){
               updateNetWorkStatus()
            }
        }

    }

    private fun updateNetWorkStatus() {
        //获取当前的网络状态
        val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

        //获取当前活跃的network对象
        val network = cm.activeNetwork

        //获取网络的能力描述
        val networkCapabilities = cm.getNetworkCapabilities(network)

        //判断网络是否可用
        val isConnected = networkCapabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true

        binding.tvNetworkStatus.text = if (isConnected) "网络可用" else "网络不可用"
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)



        registerReceivers()

        binding.btnGoToB.setOnClickListener {
            startActivity(Intent(this, BroadcastTwoActivity::class.java))
        }
    }


    fun registerReceivers(){
        //注册广播 页面间通信
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
            registerReceiver(messageReceiver, IntentFilter("com.bitcat.message"), Context.RECEIVER_EXPORTED)
        }else{
            registerReceiver(messageReceiver, IntentFilter("com.bitcat.message"))
        }

        //注册广播 监听网络状态
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
            registerReceiver(messageReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION), Context.RECEIVER_EXPORTED)
        }else{
            registerReceiver(messageReceiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
        }
    }
}